<template>
    <van-field
        :prop="field.id"
        :placeholder="field.placeholder"
        v-model="value"
        input-align="right"
        readonly
        is-link
        @click="showPicker[field.id] = true"
        :key="field.id"
        :rules="rules">
        <template #label>
            <span
                v-if="field.isrequired"
                class="red">*</span>
            <span>{{field.label}}</span>
        </template>
    </van-field>
    <van-popup
        round
        v-model:show="showPicker[field.id]"
        position="bottom"
        :key="field.id">
        <van-picker
            :columns="field.columns"
            :ref="'picker'+field.id"
            @confirm="onConfirm"
            :default-index="defaultIndex"
            @cancel="showPicker[field.id] = false"
            :key="field.id">
        </van-picker>
    </van-popup>
</template>
<script>
import { reactive, toRefs, watch, toRef } from 'vue';

export default {
    props: {
        field: {
            type: Object,
            default () {
                return {
                    id: 'prop',
                    placeholder: 'placeholder',
                    label: 'label',
                    columns: []
                };
            }
        },
        rules: Array,
        modelValue: [String, Number]
    },
    emits: ['update:modelValue'],
    setup (props, context) {
        const modelValue = toRef(props, 'modelValue');
        const state = reactive({
            value: '',
            showPicker: {},
            chooseItem: {},
            defaultIndex: 0
        });

        const onConfirm = (item, index) => {
            state.value = item.text;
            state.showPicker[props.field.id] = false;
            context.emit('update:modelValue', item.value);
        };

        const initValue = () => {
            if (modelValue.value) {
                props.field.columns.forEach((item, index) => {
                    if (item.value === modelValue.value) {
                        state.chooseItem = item;
                        state.defaultIndex = index;
                    }
                });
                state.value = state.chooseItem.text || modelValue.value;
            } else {
                state.value = '';
                state.defaultIndex = 0;
            }
        };

        watch(modelValue, (newVal, oldVal) => {
            initValue();
        }, { immediate: true });

        return {
            ...toRefs(state),
            onConfirm
        };
    }
};
</script>
